import { registerNode, registerEdge, Arrow,Util } from '@antv/g6'
import { nextTick } from 'vue'
var clickRect = []   //点击节点高亮的图形元素(若是移入移出的是该数组的元素，则直接返回)
var edgeClick = []
var fontSize  = 12
var minWidth = 160
var maxWidth = 300
var textWidth = 0
var nodes = []   //画布上所有的节点
  // 文本超出隐藏 (字段, 最大长度, 字体大小)
  const fittingString = (str) => {
      const ellipsis = '...';
      const ellipsisLength = Util.getTextSize(ellipsis, fontSize)[0];
      let currentWidth = 0
      let res = str;
      const pattern = new RegExp('[\u4E00-\u9FA5]+'); // distinguish the Chinese charactors and letters
      str.split('').forEach((letter,i) => {
          if (currentWidth > maxWidth - ellipsisLength) return;
          if (pattern.test(letter)) {
              // Chinese charactors
              currentWidth += fontSize;
          } else {
              // get the width of single letter according to the fontSize
              currentWidth += Util.getLetterWidth(letter, fontSize);
          }
          if (currentWidth > maxWidth - ellipsisLength) {
              res = `${str.substr(0,i)}${ellipsis}`;
          }
      });
      return res;
  };
  // 获取文本的长度
  const getTextSize = (str) => {
      let width = Util.getTextSize(str, fontSize)[0];
      textWidth = width
      return width > maxWidth ? maxWidth : (width < minWidth ? minWidth : width);

  }

/**
 * 高亮上游
 */
 function highlightUp(edges, eventTarget,event) {
  // try{
    edges.map(item => {
      const edgeData = item.getModel()  //获取到线的数据
      if (edgeData.targetKey === eventTarget.attr('name')) { //移入节点相关联的线高亮
        if(item.getKeyShape().attr('name') === 'bloodEdge'||item.getKeyShape().attr('name') === 'selfEdge'){
          item.getKeyShape().attr({
            endArrow: {
              path: 'M 0,0 L 8,4 L 8,-4 Z',
              fill: '#000',
              stroke: '#000'
            }, stroke: '#000'
          })
        }else{
          item.toFront()
          item.getKeyShape().attr({
            startArrow: {
              path: Arrow.circle(3, 0),
              fill: '#fff',
              stroke: '#000'
            },
            endArrow: {
              path: Arrow.circle(3, 0),
              fill: '#fff',
              stroke: '#000'
            },stroke: '#000'
          })
        }
        if(edgeData.source == edgeData.target&&edgeData.targetKey == edgeData.sourceKey){
          return
        }
        const targetG = item.getTarget().getContainer()  //获取到目标节点容器
        const resourceG = item.getSource().getContainer()  //获取到源节点容器
        const resourceRect = resourceG.findAll((itemG) => {
          return itemG.attr('name') === edgeData.sourceKey
        })
        if (resourceRect.length !== 0) {
          resourceRect[0].attr({ fill: '#ddd' })
          if(event==='mousedown'){
            edgeClick.push(item)  //点击选中的线
            clickRect.push(resourceRect[0])
          }
        }
        //下游高亮
        if (item.getSource().getEdges().length !== 0 && resourceRect.length !== 0) {
          highlightUp(item.getSource().getEdges(), resourceRect[0])
        }
      }
    
  })
  // }catch(err){
  //   console.log(err)
  // }
  
}
/**
 * 
 * @param {*} edges 当前节点相关联的连线
 * @param {*} fieldKey 当前节点下对应字段的名称(key)
 * @param {*} eventTarget 移入事件的图形元素(rect)
 * @param {*} event 什么事件
 * @param {*} clickRect 点击选中的元素(array)
 */
function highlightDown(edges, eventTarget,event,clickRect) {
  // try{
    edges.map(item => {
      const edgeData = item.getModel()  //获取到线的数据
      // if (edgeData.sourceKey === eventTarget.attr('name') || edgeData.targetKey === eventTarget.attr('name')) { //移入节点相关联的线高亮
      if (edgeData.sourceKey === eventTarget.attr('name')) { //移入节点相关联的线高亮
        if(item.getKeyShape().attr('name') === 'bloodEdge'||item.getKeyShape().attr('name') === 'selfEdge'){
          item.getKeyShape().attr({
            endArrow: {
              path: 'M 0,0 L 8,4 L 8,-4 Z',
              fill: '#000',
              stroke: '#000'
            }, stroke: '#000'
          })
        }else{
          item.toFront()
          item.getKeyShape().attr({
            startArrow: {
              path: Arrow.circle(3, 0),
              fill: '#fff',
              stroke: '#000'
            },
            endArrow: {
              path: Arrow.circle(3, 0),
              fill: '#fff',
              stroke: '#000'
            },stroke: '#000'
          })
        }
        if(edgeData.source == edgeData.target&&edgeData.targetKey == edgeData.sourceKey){
          return
        }
        const targetG = item.getTarget().getContainer()  //获取到目标节点容器
        const resourceG = item.getSource().getContainer()  //获取到源节点容器
        const targetRect = targetG.findAll((itemG) => {
          return itemG.attr('name') === edgeData.targetKey
        })
        if (targetRect.length !== 0) {
          targetRect[0].attr({ fill: '#ddd' })
          if(event==='mousedown'){
            edgeClick.push(item)  //点击选中的线
            clickRect.push(targetRect[0])
          }
        }
        //下游高亮
        if (item.getTarget().getEdges().length !== 0 && targetRect.length !== 0) {
          highlightDown(item.getTarget().getEdges(), targetRect[0])
        }
      }
    
  })
  // }catch(err){
  //   console.log(err)
  // }
  
}
function reSetHightDown(edges, eventTarget) {
  edges.forEach(item => {
    const edgeData = item.getModel()  //获取到线的数据
    if (edgeData.sourceKey === eventTarget.attr('name')) {
      if(item.getKeyShape().attr('name') === 'bloodEdge'||item.getKeyShape().attr('name') === 'selfEdge'){
        item.getKeyShape().attr({
          endArrow: {
            path: 'M 0,0 L 8,4 L 8,-4 Z',
            fill: '#ababab',
            stroke: '#ababab'
          }, stroke: '#ababab'
        })
      }else{
        edgeClick.forEach(ed=>{
          ed.toFront()
        })
        item.toBack()
        item.getKeyShape().attr({
          startArrow: {
            path: Arrow.circle(3, 0),
            fill: '#fff',
            stroke: '#ababab'
          },
          endArrow: {
            path: Arrow.circle(3, 0),
            fill: '#fff',
            stroke: '#ababab'
          },stroke:'#ababab'
        })
      }
      if(edgeData.source == edgeData.target&&edgeData.targetKey == edgeData.sourceKey){
        return
      }
      const targetG = item.getTarget().getContainer()  //获取到目标节点容器
      const resourceG = item.getSource().getContainer()  //获取到源节点容器
      const targetRect = targetG.findAll((itemG) => {
        return itemG.attr('name') === edgeData.targetKey
      })
      if(targetRect.length!==0){
        targetRect[0].attr({fill:'#fff'})
      }
       //下游 取消高亮
       if (item.getTarget().getEdges().length !== 0 && targetRect.length !== 0) {
        reSetHightDown(item.getTarget().getEdges(), targetRect[0])
       }
    }
  })
}
function reSetHightUp(edges, eventTarget) {
  edges.forEach(item => {
    const edgeData = item.getModel()  //获取到线的数据
    if (edgeData.targetKey === eventTarget.attr('name')) {
      if(item.getKeyShape().attr('name') === 'bloodEdge'||item.getKeyShape().attr('name') === 'selfEdge'){
        item.getKeyShape().attr({
          endArrow: {
            path: 'M 0,0 L 8,4 L 8,-4 Z',
            fill: '#ababab',
            stroke: '#ababab'
          }, stroke: '#ababab'
        })
      }else{
        edgeClick.forEach(ed=>{
          ed.toFront()
        })
        item.toBack()
        item.getKeyShape().attr({
          startArrow: {
            path: Arrow.circle(3, 0),
            fill: '#fff',
            stroke: '#ababab'
          },
          endArrow: {
            path: Arrow.circle(3, 0),
            fill: '#fff',
            stroke: '#ababab'
          },stroke:'#ababab'
        })
      }
      if(edgeData.source == edgeData.target&&edgeData.targetKey == edgeData.sourceKey){
        return
      }
      const targetG = item.getTarget().getContainer()  //获取到目标节点容器
      const resourceG = item.getSource().getContainer()  //获取到源节点容器
      const resourceRect = resourceG.findAll((itemG) => {
        return itemG.attr('name') === edgeData.sourceKey
      })
      if(resourceRect.length!=0){
        resourceRect[0].attr({fill:'#fff'})
      }
       //下游 取消高亮
       if (item.getSource().getEdges().length !== 0 && resourceRect.length !== 0) {
        reSetHightUp(item.getSource().getEdges(), resourceRect[0])
       }
    }
  })
}

export const bloodNode = registerNode(
  'bloodNode',
  {
    options: {
      style: {},
      stateStyles: {
        hover: {},
        selected: {
          'rect':{
            stroke:'red'
          }
          
        }
      }
    },
    /**
     * 绘制节点，包含文本
    */
    draw(cfg, group) {
      const node = group.cfg.item   //当前节点
      const edges = node.getEdges()  //当前节点相关联的连线
      nodes.push(node)
      console.log(cfg)
      const labelWidth = getTextSize(fittingString(cfg.label))
      const fieldWidthArr = []
      cfg.field.forEach(fie=>{
        fieldWidthArr.push(getTextSize(fittingString(fie.key.split('/')[1])))
      })
      const maxField = Math.max(...fieldWidthArr)
      let groupWidth = maxField>labelWidth?maxField:labelWidth
      groupWidth = groupWidth + 20
      console.log(groupWidth)
      const keyShape = group.addShape('rect', {
        attrs: {
          // width: 160,
          width:groupWidth,
          height: 20 + cfg.field.length * 16,
          stroke: '#91c051',
          lineWidth:2,
          radius: [2, 2, 0, 0]
        },
      })
      const titleGroup = group.addGroup({
        id: 'titleGroup'
      })
      const titleRect = titleGroup.addShape({
        type: 'rect',
        attrs: {
          cursor:'pointer',
          // width: 160,
          width:groupWidth,
          height: 20,
          fill: '#91c051',
          radius: [2, 2, 0, 0]
        },
        name: 'tooltip-response', //用于区分需要tooltip提示的元素
        // draggable: true
      })
      const titleText = titleGroup.addShape({
        type: 'text',
        name: 'tooltip-response', //用于区分需要tooltip提示的元素
        attrs: {
          cursor:'pointer',
          // x: 80,
          text: fittingString(cfg.label),
          x:groupWidth/2 - Util.getTextSize(fittingString(cfg.label), fontSize)[0]/2+3,
          y: 10,
          // textBaseline: 'middle',
          // text: cfg.label,
          fill: '#fff',
          // textAlign: 'center',
          fontSize: fontSize,
          textAlign: 'left',
          textBaseline: 'middle',
        }
      })
      if (cfg.field && cfg.field.length) {
        const fieldGroup = group.addGroup({
          id: 'fieldGroup'
        })
        for (let i = 0; i < cfg.field.length; i++) {
          const fieldRect = fieldGroup.addShape({
            type: 'rect',
            attrs: {
              cursor:'pointer',
              name: cfg.field[i].key,
              width: groupWidth,
              height: 16,
              x: 0,
              y: 20 + i * 16,
              fill: '#fff',
              // stroke: 'red'
            },
          })
          const fieldText = fieldGroup.addShape({
            type: 'text',
            attrs: {
              cursor:'pointer',
              // text: cfg.field[i].key.split('/')[1],
              text: fittingString(cfg.field[i].key.split('/')[1]),
              x:8,
              y: 28 + i * 16,
              textBaseline: 'middle',
              fill: 'rgba(0, 0, 0, .85)',
              fontSize: 12
            },
          })
          fieldGroup.addShape('circle', {
            attrs: {
              x: 0,
              y: 28 + i * 16,
              r: 0,
              stroke: '#096DD9',
              // fill: 'white',
              lineWidth: 1
            }
          })
          fieldGroup.addShape('circle', {
            attrs: {
              // x: getTextSize(cfg.label) + 20,
              x: groupWidth,
              y: 28 + i * 16,
              r: 0,
              stroke: '#096DD9',
              // fill: 'white',
              lineWidth: 1
            }
          })
          //点击事件
          fieldRect.on('mousedown', (e) => {
            nodes.forEach(node=>{
              node.getEdges().forEach(edge => {
                nextTick(()=>{
                  console.log(edge,edge.getKeyShape().attr('name'))
                  if(edge.getKeyShape().attr('name') !== undefined){
                     if(edge.getKeyShape().attr('name') === 'bloodEdge'||edge.getKeyShape().attr('name') === 'selfEdge'){
                      edge.getKeyShape().attr({
                        endArrow: {
                          path: 'M 0,0 L 8,4 L 8,-4 Z',
                          fill: '#ababab',
                          stroke: '#ababab'
                        }, stroke: '#ababab'
                      })
                    }else{
                      edge.getKeyShape().attr({
                        startArrow: {
                          path: Arrow.circle(3, 0),
                          fill: '#fff',
                          stroke: '#ababab'
                        },
                        endArrow: {
                          path: Arrow.circle(3, 0),
                          fill: '#fff',
                          stroke: '#ababab'
                        },stroke:'#ababab'
                      })
                    }
                  }
                 
                })
                
              })
              node.getContainer().findAll(item=>{
                if(item.get('type') == 'rect'&&item.attr('name') !== undefined){
                  item.attr({fill:'#fff'})
                }
              })
            })
            clickRect = []
            edgeClick = []
            clickRect.push(fieldRect)
            nextTick(() => {
              highlightDown(edges, e.target,'mousedown',clickRect)
              highlightUp(edges, e.target,'mousedown',clickRect)
              e.target.attr({ fill: '#faebd7' })   //当前节点黄色的高亮
            })
          })
          fieldText.on('mousedown',(e) => {
            nodes.forEach(node=>{
              node.getEdges().forEach(edge => {
                nextTick(()=>{
                  if(edge.getKeyShape().attr('name')!==undefined){
                    if(edge.getKeyShape().attr('name') === 'bloodEdge'||edge.getKeyShape().attr('name') === 'selfEdge'){
                      edge.getKeyShape().attr({
                        endArrow: {
                          path: 'M 0,0 L 8,4 L 8,-4 Z',
                          fill: '#ababab',
                          stroke: '#ababab'
                        }, stroke: '#ababab'
                      })
                    }else{
                      edge.getKeyShape().attr({
                        startArrow: {
                          path: Arrow.circle(3, 0),
                          fill: '#fff',
                          stroke: '#ababab'
                        },
                        endArrow: {
                          path: Arrow.circle(3, 0),
                          fill: '#fff',
                          stroke: '#ababab'
                        },stroke:'#ababab'
                      })
                    }
                  }
                })
                
              })
              node.getContainer().findAll(item=>{
                if(item.get('type') == 'rect'&&item.attr('name') !== undefined){
                  item.attr({fill:'#fff'})
                }
              })
            })
            clickRect = []
            edgeClick = []

            clickRect.push(fieldRect)
            nextTick(() => {
              highlightDown(edges,fieldRect,'mousedown',clickRect)
              highlightUp(edges, fieldRect,'mousedown',clickRect)
              fieldRect.attr({ fill: '#faebd7' })   //当前节点黄色的高亮
            })
          })

          //移入移出事件
          fieldRect.on('mouseenter', (e) => {
            if(clickRect.indexOf(e.target) !== -1){
              return
            }
            nextTick(() => {
              highlightDown(edges, e.target)
              highlightUp(edges, e.target)
              e.target.attr({ fill: '#faebd7' })   //当前节点黄色的高亮
            })
          })
          fieldRect.on('mouseleave', (e) => {
            if(clickRect.indexOf(e.target) !== -1){
              return
            }
            nextTick(() => {
              reSetHightDown(edges, e.target)
              reSetHightUp(edges, e.target)
              e.target.attr({ fill: '#fff' })
            })
          })
          fieldText.on('mouseenter', (e) => {
            if(clickRect.indexOf(fieldRect) !== -1){
              return
            }
            nextTick(() => {
              highlightDown(edges, fieldRect)
              highlightUp(edges, fieldRect)
              fieldRect.attr({ fill: '#faebd7' })
            })
          })
          fieldText.on('mouseleave', (e) => {
            if(clickRect.indexOf(fieldRect) !== -1){
              return
            }
            nextTick(() => {
              reSetHightDown(edges, fieldRect)
              reSetHightUp(edges, fieldRect)
              fieldRect.attr({ fill: '#fff' })
            })
          })

        }
      }
      return keyShape
    },
    /**
     * 绘制后的附加操作
     * @param  {Object} cfg 节点的配置项
     * @param  {G.Group} group 图形分组，节点中图形对象的容器
    */
    afterDraw(cfg, group) {

    },
    /**
     * 更新节点，包含文本
    */
    update(cfg, node) {

    },
    /**
     * 更新节点后的操作，一般同 afterDraw 配合使用
    */
    afterUpdate(cfg, node) {

    },
    /**
     * 响应节点的状态变化
    */
    setState(name, value, node) {

    },
    /**
     * 获取锚点（相关边的连入点）
    */
    getAnchorPoints(cfg) {
      return [
        [0, 0],
        [1, 0]
      ]
    }
  },
  // 继承内置节点类型的名字，例如基类 'single-node'，或 'circle', 'rect' 等
  // 当不指定该参数则代表不继承任何内置节点类型
  'rect'
)

export const bloodEdge = registerEdge(
  'bloodEdge',
  {
    draw(cfg, group) {
      const edge = group.cfg.item
      const sourceNode = edge.getSource().getModel()
      const sourceWidth = edge.getSource().getKeyShape().attr('width')
      const targetNode = edge.getTarget().getModel()

      const sourceIndex = sourceNode.field.findIndex(
        (e) => e.key === cfg.sourceKey
      )

      const sourceStartIndex = sourceNode.startIndex || 0

      let sourceY = 20

      if (sourceIndex > sourceStartIndex - 1) {
        sourceY = 20 + (sourceIndex - sourceStartIndex + 0.5) * 16
        // sourceY = Math.min(sourceY, 160)
      }

      const targetIndex = targetNode.field.findIndex(
        (e) => e.key === cfg.targetKey
      )
      console.log(targetIndex)
      const targetStartIndex = targetNode.startIndex || 0
        console.log(targetStartIndex)
      let targetY = 20

      if (targetIndex > targetStartIndex - 1) {
        targetY = 20 + (targetIndex - targetStartIndex + 0.5) * 16
        // targetY = Math.min(targetY, 160)
      }

      const startPoint = {
        ...cfg.startPoint
      }
      const endPoint = {
        ...cfg.endPoint
      }
      var bloodEdgePath = []
      if(cfg.source === cfg.target&&cfg.targetKey == cfg.sourceKey){
        startPoint.y = startPoint.y + sourceY
        endPoint.y = startPoint.y 
        startPoint.x = startPoint.x + sourceWidth
        
        const controlPoint = {}
        const controlPoint1 = {}
        const controlPoint2 = {}
        controlPoint.x = endPoint.x + (startPoint.x - endPoint.x)/2
        controlPoint.y = endPoint.y + sourceNode.field.length*16 + sourceIndex*16
        controlPoint1.x = endPoint.x - 2*(controlPoint.x - endPoint.x)
        controlPoint2.x = startPoint.x + 2*(controlPoint.x - endPoint.x)
        bloodEdgePath = [
          ['M', startPoint.x + 2, startPoint.y],
          [
           'C',controlPoint2.x,controlPoint.y,controlPoint1.x,controlPoint.y,endPoint.x , endPoint.y
          ]
        ]
      }else{
        startPoint.y = startPoint.y + sourceY
        endPoint.y = endPoint.y + targetY
        bloodEdgePath = [
          ['M', startPoint.x, startPoint.y],
          [
            'C',
            endPoint.x / 3 + (2 / 3) * startPoint.x,
            startPoint.y,
            endPoint.x / 3 + (2 / 3) * startPoint.x,
            endPoint.y,
            endPoint.x,
            endPoint.y
          ]
        ]
      }
      
      console.log(startPoint,endPoint)
      let shape
      shape = group.addShape('path', {
        attrs: {
          name:'bloodEdge',
          stroke: '#ababab',
          path: bloodEdgePath,
          endArrow: {
            path: 'M 0,0 L 8,4 L 8,-4 Z',
            fill: '#ababab',
            stroke: '#ababab'
          }
        },
        name: 'path-shape'
      })

      return shape
    }
  }
)

export const erEdge = registerEdge(
  'erEdge',
  {
    draw(cfg, group) {
      const edge = group.cfg.item
      const sourceNode = edge.getSource().getModel()
      const sourceWidth = edge.getSource().getKeyShape().attr('width')
      const targetNode = edge.getTarget().getModel()
      
      const sourceIndex = sourceNode.field.findIndex(
        (e) => e.key === cfg.sourceKey
      )

      const sourceStartIndex = sourceNode.startIndex || 0

      let sourceY = 20

      if (sourceIndex > sourceStartIndex - 1) {
        sourceY = 20 + (sourceIndex - sourceStartIndex + 0.5) * 16
        // sourceY = Math.min(sourceY, 160)
      }

      const targetIndex = targetNode.field.findIndex(
        (e) => e.key === cfg.targetKey
      )

      const targetStartIndex = targetNode.startIndex || 0

      let targetY = 20

      if (targetIndex > targetStartIndex - 1) {
        targetY = 20 + (targetIndex - targetStartIndex + 0.5) * 16
        // targetY = Math.min(targetY, 160)
      }

      const startPoint = {
        ...cfg.startPoint
      }
      const endPoint = {
        ...cfg.endPoint
      }
      var erEdgePath = []
      if(cfg.source === cfg.target&&cfg.targetKey == cfg.sourceKey){
        startPoint.y = startPoint.y + sourceY
        endPoint.y = startPoint.y 
        startPoint.x = startPoint.x + sourceWidth
        
        const controlPoint = {}
        const controlPoint1 = {}
        const controlPoint2 = {}
        controlPoint.x = endPoint.x + (startPoint.x - endPoint.x)/2
        controlPoint.y = endPoint.y + sourceNode.field.length*16 + sourceIndex*16
        controlPoint1.x = endPoint.x - 2*(controlPoint.x - endPoint.x)
        controlPoint2.x = startPoint.x + 2*(controlPoint.x - endPoint.x)
        erEdgePath = [
          ['M', startPoint.x + 2, startPoint.y],
          [
           'C',controlPoint2.x,controlPoint.y,controlPoint1.x,controlPoint.y,endPoint.x , endPoint.y
          ]
        ]
      }else{
        startPoint.y = startPoint.y + sourceY
        endPoint.y = endPoint.y + targetY
        erEdgePath = [
          ['M', startPoint.x, startPoint.y],
          ['L', endPoint.x / 3 + (2 / 3) * startPoint.x, startPoint.y],
          ['L', endPoint.x / 3 + (2 / 3) * startPoint.x, endPoint.y],
          ['L', endPoint.x, endPoint.y]
        ]
      }
      
       
      let shape
      shape = group.addShape('path', {
        attrs: {
          name:'erEdge',
          stroke: '#ababab',
          path: erEdgePath,
          startArrow: {
            path: Arrow.circle(3, 0),
            fill: '#fff',
            stroke: '#ababab'
          },
          endArrow: {
            path: Arrow.circle(3, 0),
            fill: '#fff',
            stroke: '#ababab'
          }
        },
        name: 'path-shape'
      })

      return shape
    }
  }
)
export const selfEdge = registerEdge(
  'selfEdge',
  {
    draw(cfg, group) {
      const edge = group.cfg.item
      const sourceNode = edge.getSource().getModel()
      const sourceWidth = edge.getSource().getKeyShape().attr('width')
      const sourceIndex = sourceNode.field.findIndex(
        (e) => e.key === cfg.sourceKey
      )

      const sourceStartIndex = sourceNode.startIndex || 0

      let sourceY = 20

      if (sourceIndex > sourceStartIndex - 1) {
        sourceY = 20 + (sourceIndex - sourceStartIndex + 0.5) * 16
        // sourceY = Math.min(sourceY, 160)
      }

      const startPoint = {
        ...cfg.startPoint
      }
      const endPoint = {
        ...cfg.endPoint
      }

      startPoint.y = startPoint.y + sourceY
      endPoint.y = startPoint.y 
      startPoint.x = startPoint.x + sourceWidth
      
      const controlPoint = {}
      const controlPoint1 = {}
      const controlPoint2 = {}
      controlPoint.x = endPoint.x + (startPoint.x - endPoint.x)/2
      controlPoint.y = endPoint.y + sourceNode.field.length*16 + sourceIndex*16
      controlPoint1.x = endPoint.x - (controlPoint.x - endPoint.x)
      controlPoint2.x = startPoint.x + (controlPoint.x - endPoint.x)
      console.log(sourceNode.field.length,controlPoint1.x,controlPoint2.x,controlPoint.y,startPoint,endPoint)
      let shape
      shape = group.addShape('path', {
        // loopCfg: {
        //   position: 'left',
        //   dist: 100,
        //   clockwise: false,
        // },
        zIndex:30,
        attrs: {
          name:'selfEdge',
          stroke: '#ababab',
          path: [
            ['M', startPoint.x + 2, startPoint.y],
            [
             'C',controlPoint2.x,controlPoint.y,controlPoint1.x,controlPoint.y,endPoint.x , endPoint.y
            ]
          ],
          endArrow: {
            path: 'M 0,0 L 8,4 L 8,-4 Z',
            fill: '#ababab',
            stroke: '#ababab'
          }
        },
        name: 'path-shape'
      })

      return shape
    }
  }, 
  // 'loop'
  
)

